package jsyf.oa.service.report.newAppReport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.report.newAppReport.NewAppReportForRMDao;
import jsyf.oa.dao.system.CompanyDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.system.WechatContactsDao;
import jsyf.oa.facade.report.newAppReport.NewAppReportForRMFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@SuppressWarnings("all")
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class NewAppReportForRMService implements NewAppReportForRMFacade {

    @Autowired
    private NewAppReportForRMDao newAppReportForRMDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private WechatContactsDao wechatContactsDao;

    /*获取个人*/
    @Override
    public JSONObject getForPersonalIntentCustomerList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String nowTime = "";
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            nowTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            nowTime = dateTime.substring(0, 7);
        }
        List<JSONObject> records = newAppReportForRMDao.getForPersonalIntentCustomerList(userId);
        JSONObject result = new JSONObject();
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getSignPersonByToday(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String nowTime = "";
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        } else {
            nowTime = dateTime;
        }
        JSONObject result = new JSONObject();
        //获取个人考勤信息,判断出勤、缺勤、请假
        JSONObject signToday = newAppReportForRMDao.getSignPersonByToday(userId, nowTime);
        JSONObject leaveToday = newAppReportForRMDao.getLeavePersonByToday(userId, nowTime);
        if (null == signToday && null == leaveToday) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userDao.getById(userId).getName());
            result.put("signState", "2");
            result.put("result", jsonObject);
            return result;
        }
        if (null == signToday) {
            result.put("signState", "0");
            result.put("result", leaveToday);
            return result;
        } else {
            result.put("signState", "1");
            result.put("result", signToday);
            return result;
        }
        //1签到/2缺勤/0请假
    }

    @Override
    public JSONObject getForPersonalCostByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        List<JSONObject> personalCostList = newAppReportForRMDao.getForPersonalCostByUserIdAndDateTime(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", personalCostList);
        return result;
    }

    @Override
    public JSONObject getForPersonalDayByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");//0-电/1-面
        String status = jsonParams.getString("status");//0-AM/1-PM

        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        String nowTime = "";
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        } else {
            nowTime = dateTime.substring(0, 7);
        }
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        StringBuffer condition = new StringBuffer();
        condition.append(" AND (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> jsonObjects = newAppReportForRMDao.getForPersonalDayByUserIdAndDateTime(userId, dateTime, Integer.valueOf(type), Integer.valueOf(status), condition, requestPage, pageSize);
        int recordCount = newAppReportForRMDao.getForPersonalDayByUserIdAndDateTimePageCount(userId, dateTime, Integer.valueOf(type), Integer.valueOf(status), condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", jsonObjects);
        objResult.put("pager", objPager);

        return objResult;
    }

    @Override
    public JSONObject getTodayPlanByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String date = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (!StringUtils.isBlank(dateTime)) {
            try {
                date = DateUtils.getBeforeDate(sdf.parse(dateTime), 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            date = DateUtils.getYesterday();
        }
        List<JSONObject> tomorrowVisitList = newAppReportForRMDao.getTomorrowVisitToday(userId, date);
        JSONObject result = new JSONObject();
        result.put("records", tomorrowVisitList);
        return result;
    }

    @Override
    public JSONObject getFirstVisitAndSignForToday(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        JSONObject firstVisitAndSign = newAppReportForRMDao.getFirstVisitAndSignForToday(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", firstVisitAndSign);
        return result;
    }

    @Override
    public JSONObject getVisitCustomerByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");//0-电/1-面
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        List<JSONObject> visitCustomerList = newAppReportForRMDao.getVisitCustomerByUserIdAndDateTime(userId, dateTime, Integer.parseInt(type));
        JSONObject result = new JSONObject();
        result.put("records", visitCustomerList);
        return result;
    }

    @Override
    public JSONObject getCustomerNumByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        JSONObject customerNum = newAppReportForRMDao.getCustomerNumByuserIdAndDateTime(userId, dateTime, Integer.parseInt(type));
        JSONObject result = new JSONObject();
        result.put("records", customerNum);
        return result;
    }

    @Override
    public JSONObject getWechatShareList(String jsonData) {
        JSONObject jsonObject = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonObject.getString("dateTime");
        String userId = jsonObject.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        String companyIds = "";
        List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                String selectCompanyId = userList.get(i).getString("companyId");
                String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                //如果有下级
                if (!StringUtils.isBlank(ids)) {
                    //如果有多个下级
                    if (ids.indexOf(",") >= 0) {
                        String[] idsSplit = ids.split(",");
                        for (String id : idsSplit) {
                            companyIds += "'" + id + "',";
                        }
                    } else {
                        //如果只有一个下级
                        companyIds += "'" + ids + "',";
                    }
                }
                companyIds += "'" + selectCompanyId + "',";
            }
            companyIds = companyIds.substring(0, companyIds.length() - 1);
        } else {
            companyIds = "''";
        }
        List<JSONObject> wechatlist = newAppReportForRMDao.getTodayWechatShareList(dateTime, userId, companyIds);
        if (null != wechatlist && wechatlist.size() > 0) {
            wechatlist = getWechatContact(wechatlist, userId, dateTime);
        }
        JSONObject result = new JSONObject();
        result.put("records", wechatlist);
        return result;
    }

    @Override
    public JSONObject getSaleList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        List<JSONObject> listManagerList = newAppReportForRMDao.getNewSaleManagerList(userId, dateTime);//区域经理
        JSONObject result = new JSONObject();
        result.put("records", listManagerList);
        return result;
    }

    public List<JSONObject> getWechatContact(List<JSONObject> wechatlist, String userId, String dateTime) {
        List<JSONObject> contacts = new ArrayList<JSONObject>();

        for (int i = 0; i < wechatlist.size() - 1; i++) {
            int j = i;
            int iDayContacts = Integer.parseInt(wechatlist.get(i).getString("contacts"));
            int iAdd1DayContacts = Integer.parseInt(wechatlist.get(j + 1).getString("contacts"));
            wechatlist.get(i).put("num", iDayContacts - iAdd1DayContacts);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        try {
            date = sdf.parse(wechatlist.get(wechatlist.size() - 1).getString("date"));
        } catch (ParseException px) {
            px.printStackTrace();
        }

        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();

        String yesterday = sdf.format(date);

        List<JSONObject> wechatContacts = wechatContactsDao.getJSONListByCondition(" AND USER_ID=? AND LEFT(t_wechat_friends_contacts.CREATE_TIME,7)=?", new Object[]{userId, yesterday});
        JSONObject wechatContact = null;
        if (null != wechatContacts && wechatContacts.size() > 0) {
            wechatContact = wechatContacts.get(0);
        }
        if (null != wechatContact) {
            int contactNum1 = Integer.parseInt(wechatlist.get(wechatlist.size() - 1).getString("contacts"));
            int contactNum2 = Integer.parseInt(wechatContact.getString("contacts"));
            wechatlist.get(wechatlist.size() - 1).put("num", contactNum1 - contactNum2);
        } else {
            wechatlist.get(wechatlist.size() - 1).put("num", 0);
        }

        return wechatlist;
    }

    @Override
    public JSONObject getAllCustomerForRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        StringBuffer condition = new StringBuffer();
        condition.append("having (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> allCustomer = newAppReportForRMDao.getAllCustomerForRM(userId, type, condition, requestPage, pageSize);
        int recordCount = newAppReportForRMDao.getAllCustomerPageCount(userId, type, condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", allCustomer);
        objResult.put("pager", objPager);
        return objResult;

    }


    @Override
    public JSONObject getNewCustomerForRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        StringBuffer condition = new StringBuffer();
        condition.append("and (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> newCustomer = newAppReportForRMDao.getNewCustomerForRM(userId, dateTime, type, condition, requestPage, pageSize);
        int recordCount = newAppReportForRMDao.getNewCustomerPageCount(userId, dateTime, type, condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", newCustomer);
        objResult.put("pager", objPager);
        return objResult;


    }


}
